#include "progressviewer.h"
#include "ui_progressviewer.h"
#include "includes/usercollection.h"

ProgressViewer::ProgressViewer(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ProgressViewer)
{
    ui->setupUi(this);

    connect(ui->treeWidget, SIGNAL(itemClicked(QTreeWidgetItem*,int)),parent,SLOT(playVideo(QTreeWidgetItem*,int)));

    ui->treeWidget->setColumnCount(6);
    ui->treeWidget->setColumnHidden(5, true);
    ui->treeWidget->setColumnWidth(5, 0);

    ui->treeWidget->setIconSize(QSize(30,30));

    UserCollection uc;
    uc.load("users.xml");
    foreach (User u, uc)
    {
        foreach (ProgressItem pi, u.getProgress())
        {
            QTreeWidgetItem* pti = new QTreeWidgetItem(ui->treeWidget);
            pti->setText(0, pi.getDate().toString());
            pti->setText(1, u.getName());
            pti->setIcon(1, QIcon(u.getImageFilename()));
            pti->setText(2, pi.getLessonName());
            pti->setText(3, pi.getPhraseName());
            QIcon icon;
            if (pi.getStatus() == 0) icon = QIcon(":/images/images/unhappy.png");
            else if (pi.getStatus() == 1) icon = QIcon(":/images/images/ok.png");
            else if (pi.getStatus() == 2) icon = QIcon(":/images/images/happyish.png");
            pti->setIcon(4, icon);
            pti->setData(5, Qt::UserRole, QVariant(pi.getVideoFilename()));
            ui->treeWidget->addTopLevelItem(pti);
            itemList.append(pti);
        }
    }
    for (int i = 0; i < 5; i++)
        ui->treeWidget->resizeColumnToContents(i);
    for (int i = 0; i < 5; i++)
        ui->treeWidget->setColumnWidth(i,
                                       ui->treeWidget->columnWidth(i) + 10);
    int width = 0;
    for (int i = 0; i < 5; i++)
        width += ui->treeWidget->columnWidth(i);
    ui->treeWidget->setMinimumSize(width+3, 0);

}

void ProgressViewer::filter(QString user)
{
    //rather than filtering myself i decided to use the findItems() method
    QList<QTreeWidgetItem*> filteredList = ui->treeWidget->findItems(user, Qt::MatchFixedString, 1);

    //clear() doesn't seem to work, this clears the treeWidget
    while (ui->treeWidget->topLevelItemCount() > 0)
        ui->treeWidget->takeTopLevelItem(0);

    ui->treeWidget->addTopLevelItems(filteredList);
}

ProgressViewer::~ProgressViewer()
{
    delete ui;
}

void ProgressViewer::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}
